package org.dftproject.genesis.ui.figures.zoompan;

import org.eclipse.draw2d.Viewport;
import org.eclipse.draw2d.geometry.Point;
import org.eclipse.draw2d.geometry.Rectangle;

public class CenteredViewport extends Viewport {

	public static final String CENTER_LOCATION = "centerLocation";
	
	public CenteredViewport() {
		super();
	}
	
	public CenteredViewport(boolean useTranslate) {
		super(useTranslate);
	}

	@Override
	public void readjustScrollBars() {
		if (getContents() == null)
			return;
		
		Rectangle clientArea = getClientArea();
		Rectangle contentsBounds = getContents().getBounds();

		getVerticalRangeModel().setAll(-clientArea.height, clientArea.height, contentsBounds.height + clientArea.height);
		getHorizontalRangeModel().setAll(-clientArea.width, clientArea.width, contentsBounds.width + clientArea.width);
	}
	
	@Override
	public void setViewLocation(int x, int y) {
		Point oldCenter = getViewCenter();
		super.setViewLocation(x, y);
		firePropertyChange(CENTER_LOCATION, oldCenter, getViewCenter());
	}
	
	public void setViewCenter(Point location) {
		Rectangle clientArea = getClientArea();
		setViewLocation(location.getTranslated(-clientArea.width / 2, -clientArea.height / 2));
	}

	public Point getViewCenter() {
		Rectangle clientArea = getClientArea();
		return getViewLocation().getTranslated(clientArea.width / 2, clientArea.height / 2);
	}

}
